package com.ken.forum.controller;


import com.alibaba.druid.util.StringUtils;
import com.ken.forum.common.AppResult;
import com.ken.forum.common.ResultCode;
import com.ken.forum.config.AppConfig;
import com.ken.forum.model.User;
import com.ken.forum.services.IUserService;
import com.ken.forum.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import com.ken.forum.utils.UUIDUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
//：Controller 层负责接收来自客户端的 HTTP 请求，
// 并将请求参数传递给 Service 层进行业务逻辑处理，
// 然后将处理结果返回给客户端。


@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    // 注⼊业务层
    @Resource
    private IUserService userService;

    // 指定接⼝URL映射

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //ApiParam对参数的描述;RequestRepeat:前后端交互过程中参数的KEY;NonNull非空校验

        // 校验参数的有效性
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat) || StringUtils.isEmpty(nickname)) {
            // 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 1.基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 2.处理密码
        // 2.1 校验密码和确认密码是否相等
        if (!password.equals(passwordRepeat)) {
            // 记录⽇志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2.2 加密密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        // 2.3 设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        // 3. 调⽤Service
        userService.createNormalUser(user);
        // 4. 返回
        return AppResult.success();
    }


    /**
     * ⽤⼾登录
     *
     * @param request
     * @param username ⽤⼾名
     * @param password 密码
     * @return AppResult
     */
    @ApiOperation("⽤⼾登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @ApiParam(value = "⽤⼾名") @RequestParam(value = "username") @NonNull String username,
                           @ApiParam(value = "密码") @RequestParam(value = "password") @NonNull String password) {
        // ⽤⼾登录
        User user = userService.login(username, password);
        // 获取Session
        HttpSession session = request.getSession(true);
        // 把User设置到Session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 登录成功响应
        return AppResult.success();
    }


    /**
     * 获取⽤⼾详情
     *
     * @param id ⽤⼾ id
     * @return ⽤⼾详情
     */
    @ApiOperation("获取⽤⼾详情")
    @PostMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @ApiParam(value = "⽤⼾Id") @RequestParam(value = "id", required = false) Long id) {
        // 根据参数中的Id是否为空决定返回哪个⽤⼾
        // 1. id 为空，返回当前登录⽤⼾
        // 2. id 不为空，返回指定id的⽤⼾
        User user = null;
        if (id == null) {
            // 获取Session中的⽤⼾信息
            HttpSession session = request.getSession();
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            // 根据⽤⼾Id从数据库中查询⽤⼾信息
            user = userService.selectById(id);
        }
        // 返回结果
        return AppResult.success(user);
    }


    @ApiOperation("⽤⼾退出")
    @PostMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        // 获取session对象
        HttpSession session = request.getSession();
        if (session != null) {
            // 注销session
            session.invalidate();
        }
        // 退出成功响应
        return AppResult.success();
    }


    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo(HttpServletRequest httpServletRequest,
                                      @ApiParam("用户名(用于登录)") @RequestParam(value = "username", required = false) String username,
                                      @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                      @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                      @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                      @ApiParam("电话") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                      @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname) && gender == null &&
                StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum) && StringUtils.isEmpty(remark)) {
            return AppResult.failed("要修改的信息不能全为空");
        }
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setEmail(email); // 邮箱
        updateUser.setRemark(remark); // 个人简介

        userService.modifyInfo(updateUser);

        user = userService.selectById(user.getId());

        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(@ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat,
                                    HttpServletRequest httpServletRequest) {
        //判断两次输入的密码
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);

        }
        //获取当前登录的用户信息
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //修改密码
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        //销毁当前的session
        session.invalidate();
        return AppResult.success("修改成功");

    }
}
